﻿using Microsoft.AspNetCore.Mvc;
using Renci.SshNet;
using System.Net.WebSockets;

namespace ztDataNet.Controllers
{
    /// <summary>
    /// ssh
    /// </summary>
    public class SshWebSocketController : ControllerBase
    {
        /// <summary>
        /// HandleSshWebSocketAsync
        /// </summary>
        /// <returns></returns>
        [HttpGet("/ssh")]
        public async Task HandleSshWebSocketAsync()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                using var sshClient = new SshClient("119.45.240.39", "root", "Zt04985807");
                try
                {
                    sshClient.Connect();
                    var shellStream = sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024);

                    var buffer = new byte[1024 * 4];
                    var cancellationToken = HttpContext.RequestAborted; // Use the request's cancellation token

                    while (webSocket.State == WebSocketState.Open)
                    {
                        var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
                        if (result.Count > 0)
                        {
                            // 写入到 SSH 流
                            shellStream.Write(buffer, 0, result.Count);
                            shellStream.Flush();
                        }

                        // 如果 WebSocket 接收到关闭消息，退出循环
                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            break;
                        }

                        // 从 SSH 流中读取数据
                        var bytesRead = await shellStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
                        if (bytesRead > 0)
                        {
                            // 发送到 WebSocket 客户端
                            await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, bytesRead), WebSocketMessageType.Text, true, cancellationToken);
                        }
                        cancellationToken.ThrowIfCancellationRequested();
                    }
                }
                catch (Exception ex)
                {
                    // Log the exception
                    Console.WriteLine($"An error occurred: {ex.Message}");
                }
                finally
                {
                    if (sshClient.IsConnected)
                    {
                        sshClient.Disconnect();
                    }
                }
            }
            else
            {
                HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
        }

    }
}
